# 导入uuid类
import uuid
# 导入哈希库
import hashlib
import openpyxl
import os
path=os.path.split(__file__)[0]+"guoggg.xlsx"
print(type(path))
print(path)

def get_random_str():
    #获取uuid的随机数
    uuid_val = uuid.uuid4()
    #获取uuid的随机数字符串
    uuid_str = str(uuid_val).encode('utf-8')
    #获取md5实例
    md5 = hashlib.md5()
    #拿取uuid的md5摘要
    md5.update(uuid_str)
    #返回固定长度的字符串
    print(md5.hexdigest())
    return md5.hexdigest()

get_random_str()

def write_to_excel(data,path):
    """把数据库写入到Excel"""
    # 实例化一个workbook
    workbook = openpyxl.Workbook()
    # 激活一个sheet
    sheet = workbook.active
    # 为sheet命名
    sheet.title = 'student'
    # 准备keys
    keys = data[0].keys()
    # 准备写入数据
                                               #data:   [{},{},{}]
    for index, item in enumerate(data):      #[(0,{}),(1,{}),(2,{})]
        print(22222222222)
        print(index,item)
        # 遍历每一个元素
        for k,v in enumerate(keys):
            sheet.cell(row=index + 1, column=k+ 1, value=str(item[v]))
    # 写入到文件
    workbook.save(path)

if __name__ == '__main__':
    data=[{'id': 118, 'sno': '95001', 'sname': '王小进', 'gender': '男',
           'birthday': "1998-05-12", 'mobile': '13908764888', 'email': 'wangxiaoming@abc.com',
           'address': '南京市鼓楼区元南北路88号',
            'image': '592b301efeb788d0dd5f4ace8d5929b4.JPG'},{'id': 128, 'sno': '95002', 'sname': '王2进', 'gender': '男',
           'birthday': "1998-05-12", 'mobile': '13228764888', 'email': 'wangxiaomin2g@abc.com',
           'address': '阿瑟瑞范围覆盖',
            'image': 'asdas'}]

    write_to_excel(data,path)